<?php
namespace SDXApi\Controller;

use SDXApi\Controller\AppController;

/**
 * 便利店铺模块
 * 
 * @author ^2_3^
 */
class BlstoreController extends AppController {
    
    /**
     * 便利店铺首页
     * 
     * @param int store_id 便利店ID;
     * @param int store_sn 店铺货架编号;
     * @param int user_id 用户ID;
     * 
     * @author ^2_3^
     */
    public function index() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where($where_s)->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此店铺,请联系客服;');
        }
        
        /// 红包领取
        $list_bonus = self::get_bonus_list($info_store['id'], $user_id);
        $data['list_bonus'] = $list_bonus['list'];
        $data['list_bonus_debug_msg'] = $list_bonus['msg'];
        $data['list_bonus_show_msg'] = count($list_bonus['list']).'个红包已到账!';
        $data['has_bonus'] = 0;
        if( !empty($list_bonus['list']) ) {
            $data['has_bonus'] = 1;
        }
        //-/ 提取名下红包
        $time_now = gmtime();
        $where_b = array(
            'br.store_id' => $info_store['id'],
            'br.user_id' => $user_id,
            'br.use_start_date' => array('ELT', $time_now),
            'br.use_end_date' => array('GT', $time_now),
            'br.use_time' => 0,
            'br.r_status' => 0
        );
        $list_bl = M('bl_bonus_record br')
            ->join('sdx_bonus_type bt ON bt.type_id = br.bonus_id', 'left')
            ->join('sdx_bl_bonus_set bs ON bs.bonus_id = br.bonus_id', 'left')
            ->field('
                br.id AS br_id,
            	br.user_id,
            	br.store_id,
            	br.bonus_id,
            	br.use_start_date,
            	br.use_end_date,
            	br.get_time,
                bt.type_name,
                bs.bonus_tip_name,
            	bt.min_goods_amount,
            	bt.type_money
            ')
            ->where($where_b)
            ->select();
        foreach ( $list_bl as $l_key=>$l_arr ){
            if( !empty($l_arr['bonus_tip_name']) ) {
                $list_bl[$l_key]['type_name_ori'] = $l_arr['type_name'];
                $list_bl[$l_key]['type_name'] = $l_arr['bonus_tip_name'];
            }
        }
        $list_bonus['list'] = $list_bl;
        $data['list_bonus'] = $list_bonus['list'];
//         $data['list_bonus_ori'] = $list_bonus;
        
        /// 当天红包使用次数
        $date_now = date('Y-m-d');
        $date_time = gmstr2time($date_now);
        $where_oi = array(
            'pay_time' => array(
                array('EGT', $date_time),
                array('LT', $date_time + 86400)
            ),
            'bonus_id' => array('NEQ', 0),
            'pay_status' => 2,
            'order_status' => 1,
            'user_id' => $user_id
        );
        $data['b_use_times'] = M('bl_order_info')->where( $where_oi )->count('order_id');
        $data['b_use_limit'] = 2;
        
        /// 购物车列表
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        //-/ 列表处理
        $num_goods = 0;
        $num_amount = 0;
        $list_cart = M('bl_cart')->where( $where_c )->select();
        foreach ( $list_cart as $c_key=>$c_arr ){
            //-/ 商品个数
            $num_goods += $c_arr['goods_number'];
            //-/ 商品总额
            $num_amount += $c_arr['goods_price'] * $c_arr['goods_number'];
        }
        
        $data['info_store'] = $info_store;
        $data['num_goods'] = $num_goods;
        $data['num_amount'] = $num_amount;
        $data['list_cart'] = $list_cart;
        returnApiSuccess($data);
    }
    
    /**
     * 红包领取
     * 
     * 规则:
     * [1]用户最多3个可用红包;
     * [2]周期用户只可领取一次红包;
     * [3]红包应发放数量 = 3 - 已有可用红包数量; 结果=3或2时，则按照50%概率发放1~2个红包，如果结果=1，则发放一个红包;
     * 
     * @param number $store_id 店铺ID;
     * @param number $user_id 店铺用户ID;
     * 
     * @author ^2_3^
     */
    private function get_bonus_list($store_id = 0, $user_id = 0) {
        if( empty($store_id) || empty($user_id) ) {
            throw new \Exception("提示:BlstoreController->get_bonus_list({$store_id}, {$user_id})缺少参数;");
        }
        $list_bonus = array(
            'list' => array(),
            'msg' => ''
        );
        
        /// 领取时间: 超过九时才能领取红包;
        $date = date('Y-m-d');
        $hour = date('H');
        //-/ NOTE: 12-01 由9点改成8点;
        if( $hour < 8 ) {
            $list_bonus['msg'] = '提示: 没到时间, 八点才开始哦;';
            return $list_bonus;
        }
        
        /// 有无领取：用户是否首次访问(没有领取红包记录);
        // 规则: 周期用户只可领取一次红包;
        $where_br = array(
            'user_id' => $user_id,
            'store_id' => $store_id,
            'get_time' => array('EGT', gmstr2time($date) ),
            'r_status' => 0
        );
        $info_br = M('bl_bonus_record')->where($where_br)->find();
// w_log('cyb_log', '有无领取 '.M()->getLastSql() );
        if( !empty($info_br) ) {
            $list_bonus['msg'] = '提示:已经领取;';
            return $list_bonus;
        }
        
        $week_day = date('w');
        $time_now = gmtime();
        
        /// 规则: 用户最多3个可用红包;
        $where_h = array(
            'br.store_id' => $store_id,
            'br.use_start_date' => array('ELT', $time_now),
            'br.use_end_date' => array('GT', $time_now),
            'br.use_time' => 0,
            'br.r_status' => 0
        );
        $where_h['_string'] = " br.user_id = {$user_id} OR br.user_id = 0 ";
        $num_had = M('bl_bonus_record br')->where( $where_h )->count('br.id');
// w_log( 'cyb_log', '已有红包 '.M()->getLastSql() );
        if( $num_had >= 3 ) {
            $list_bonus['msg'] = '提示:已有3个红包, 不能再领取;';
            return $list_bonus;
        }
        
        //// 有无红包: 红包列表(非随机红包; 随机红包);
        $where_bs = array(
            'bs.is_disabled' => 0,
            'week_day' =>array('like', "%{$week_day}%"),
            'bt.send_start_date' => array('ELT', $time_now),
            'bt.send_end_date' =>array('GT', $time_now),
            'bs.bl_bonus_type' => 0
        );
        $where_bs['_string'] = " (is_all = 1) OR (is_all = 0 && store_ids LIKE '%,{$store_id},%') ";
        ///
        /// 随机红包
        $where_bsr = $where_bs;
        $where_bsr['is_random'] = 1;
        $list_r_bonus = M('bl_bonus_set bs')->field('
            bs.id AS bs_id,
        	bs.bonus_id,
        	bs.week_day,
        	bs.is_all,
        	bs.store_ids,
        	bs.limit_num,
        	bs.is_random,
        	bs.is_disabled,
        	bt.type_name,
            bt.limit_send_num,
            bt.has_effective_days,
            bt.effective_days,
        	bt.send_start_date,
        	bt.send_end_date,
        	bt.use_start_date,
        	bt.use_end_date
        ')
        ->join('sdx_bonus_type bt ON bt.type_id = bs.bonus_id', 'left')
        ->where($where_bsr)
        ->select();
        $num_rb = count( $list_r_bonus );
// w_log('cyb_log', '随机红包 '.M()->getLastSql());
        ///
        /// 非随机红包
        $where_bsnr = $where_bs;
        $where_bsnr['is_random'] = 0;
        $list_nr_bonus = M('bl_bonus_set bs')->field('
            bs.id AS bs_id,
        	bs.bonus_id,
        	bs.week_day,
        	bs.is_all,
        	bs.store_ids,
        	bs.limit_num,
        	bs.is_random,
        	bs.is_disabled,
        	bt.type_name,
            bt.limit_send_num,
            bt.has_effective_days,
            bt.effective_days,
        	bt.send_start_date,
        	bt.send_end_date,
        	bt.use_start_date,
        	bt.use_end_date
        ')
        ->join('sdx_bonus_type bt ON bt.type_id = bs.bonus_id', 'left')
        ->where($where_bsnr)
        ->select();
        $num_nrb = count( $list_nr_bonus );
// w_log('cyb_log', '非随机红包 '.M()->getLastSql());
        ///
        /// 判断: 有无红包
        if( $num_rb == 0 && $num_nrb == 0 ) {
            $list_bonus['msg'] = '提示: 没有可领取红包;';
            return $list_bonus;
        }
// w_log('cyb_log', "随机红包({$num_rb}); 非随机红包({$num_nrb});");
        ///
        /// 已发红包
        $where_bg = array(
            'br.get_time' => array( 'EGT', gmstr2time($date) ),
            'br.r_status' => 0
        );
        $list_bgeted = M('bl_bonus_record br')->field('
                br.bonus_id,
                COUNT(br.id) AS count_num
            ')
            ->where($where_bg)
            ->group('br.bonus_id')
            ->select();
// w_log( 'cyb_log', '已发红包 '.M()->getLastSql() );
        ///
        /// 判断: 有无数量
        //-/ 随机红包
        foreach ( $list_bgeted as $bg_key=>$bg_arr ){
            /// 检查: 随机红包发放数量;
            foreach ( $list_r_bonus as $r_key=>$r_arr ){
                if( $bg_arr['bonus_id'] == $r_arr['bonus_id'] ) {
                    
                    //-/ 红包上限
                    if( $r_arr['limit_send_num'] > 0 && $bg_arr['count_num'] >= $r_arr['limit_send_num'] ) {
                        //unset( $list_r_bonus[$r_key] );
                        array_splice($list_r_bonus, $r_key, 1);
                        
                    }else if( $r_arr['limit_send_num'] > 0 ) {
                        $list_r_bonus[$r_key]['num_remain'] = $r_arr['limit_send_num'] - $bg_arr['count_num'];
                    }
                    
                    break;
                }
            }
        }
        //-/ 非随机红包
        foreach ( $list_bgeted as $g_key=>$g_arr ){
            /// 检查: 非随机红包发放数量;
            foreach ( $list_nr_bonus as $n_key=>$n_arr ){
                if( $g_arr['bonus_id'] == $n_arr['bonus_id'] ) {
                    
                    if( $n_arr['limit_send_num'] > 0 && $g_arr['count_num'] >= $n_arr['limit_send_num'] ) {
                        //unset( $list_nr_bonus[$n_key] );
                        array_splice($list_nr_bonus, $n_key, 1);
                        
                    }else if( $n_arr['limit_send_num'] > 0 ) {
                        $list_nr_bonus[$n_key]['num_remain'] = $n_arr['limit_send_num'] - $g_arr['count_num'];
                    }
                    
                    break;
                }
            }
        }
        
        ///
        /// 检查红包
        $num_rb = count( $list_r_bonus );
        $num_nrb = count( $list_nr_bonus );
        if( $num_rb == 0 && $num_nrb == 0 ) {
            $list_bonus['msg'] = '提示: 红包已发完;';
            return $list_bonus;
        }
// w_log('cyb_log', "红包限制: 随机红包({$num_rb}); 非随机红包({$num_nrb});");
        
        /// 判断店铺数量限制;
        $where_sb = array(
            'br.get_time' => array('EGT', gmstr2time($date)),
            'br.store_id' => $store_id,
            'br.r_status' => 0
        );
        $list_sb_num = M('bl_bonus_record br')->field('
            	br.bonus_id,
            	COUNT(br.id) AS count_num
            ')
            ->where( $where_sb )
            ->group('br.bonus_id')
            ->select();
// w_log( 'cyb_log', '店铺红包数量 '.M()->getLastSql() );
        foreach ( $list_sb_num as $sb_key=>$sb_arr ){
            $flag_do = false;
            
            //-/ 判断: 随机红包是否达到店铺红包限制数量;
            foreach ( $list_r_bonus as $lr_key=>$lr_arr ){
                if( $sb_arr['bonus_id'] == $lr_arr['bonus_id'] ) {
                    
                    if( $lr_arr['limit_num'] > 0 && $sb_arr['count_num'] >= $lr_arr['limit_num'] ) {
                        //unset( $list_r_bonus[$lr_key] );
                        array_splice($list_r_bonus, $lr_key, 1);
                        
                    }else if( $lr_arr['limit_num'] > 0 ) {
                        $list_r_bonus[$lr_key]['store_num_remain'] = $lr_arr['limit_num'] - $sb_arr['count_num'];
                    }
                    
                    $flag_do = true;
                    break;
                }
            }
            
            if( $flag_do ) {
                continue;
            }
            
            //-/ 判断: 非随机红包是否达到店铺红包限制数量;
            foreach ( $list_nr_bonus as $nb_key=>$nb_arr ){
                if( $sb_arr['bonus_id'] == $nb_arr['bonus_id'] ) {
                    if( $nb_arr['limit_num'] > 0 && $sb_arr['count_num'] >= $nb_arr['limit_num'] ) {
                        //unset( $list_nr_bonus[$nb_key] );
                        array_splice($list_nr_bonus, $nb_key, 1);
                        
                    }else if( $nb_arr['limit_num'] > 0 ) {
                        $list_nr_bonus[$nb_key]['store_num_remain'] = $nb_arr['limit_num'] - $sb_arr['count_num'];
                    }
                    
                    break;
                }
            }
        }
        
        ///
        /// 检查红包
        $num_rb = count( $list_r_bonus );
        $num_nrb = count( $list_nr_bonus );
        if( $num_rb == 0 && $num_nrb == 0 ) {
            $list_bonus['msg'] = '提示: 店铺红包已发完;';
            return $list_bonus;
        }
// w_log('cyb_log', "店铺红包限制: 随机红包({$num_rb}); 非随机红包({$num_nrb});");
        
        /// 领取位数: 获取红包领取位数，是否符合随机红包发放条件;
        $where_n = array(
            'br.store_id' => $store_id,
            'br.get_time' => array('EGT', gmstr2time($date))
        );
        $bonus_idx = M('bl_bonus_record br')->where($where_n)->count('DISTINCT br.user_id');
        $bonus_idx = $bonus_idx + 1;
// w_log('cyb_log', '领取位数 '.M()->getLastSql());
        
        /// 规则: 红包应发放数量 = 3 - 已有可用红包数量; 
        // 结果=3或2时，则按照50%概率发放1~2个红包，如果结果=1，则发放一个红包;
//         $num_bonus = 3 - $num_had;
//         if( $num_bonus >= 2 ) {
//             $num_bonus = rand(1, 2);
//         }
        // NOTE: 2017-12-01规则修改, 领取数量为 红包应发放数量 = 3 - 已有可用红包数量;
        $num_bonus = 3 - $num_had;
// w_log('cyb_log', "应发红包: {{$num_bonus}}; 第{$bonus_idx}位;");
        
        //-/ 发放随机红包: 第3~8，25~30位, 有随机红包则发一个随机红包;
        $tip = '';
        if( ( ($bonus_idx >= 3 && $bonus_idx <= 8) || ($bonus_idx >= 25 && $bonus_idx <= 30) ) &&
            $num_rb > 0 && rand(0, 6) == 1 ) {
            
            $time_r = 0;
            do {
                $time_r = $time_r + 1;
                
                $idx_r = rand(0, $num_rb-1);
                $arr_rbonus = $list_r_bonus[$idx_r];
                
                $flag_r = self::generate_bonus( $user_id, $store_id, $arr_rbonus );
                if( $flag_r ) {
                    $list_bonus['list'][] = $arr_rbonus;
                    $num_bonus = $num_bonus - 1;
                
                }else {
                    $tip .= "{$arr_rbonus['type_name']}[{$arr_rbonus['bonus_id']}]领取随机红包失败; ";
                }
                
            }while ( !$flag_r && $time_r < $num_rb*3);
            
        }
        //-/ 发放非随机红包
        $num_loop = $num_bonus;
        for( $i=1; $i<=$num_loop; $i++ ) {
            $num_nrb = count( $list_nr_bonus );
            
            if( $num_bonus > 0 && $num_nrb >0 ) {
            
                $time_nr = 0;
                do {
                    $time_nr = $time_nr + 1;
            
                    $idx_nr = rand(0, $num_nrb-1);
                    $arr_nrbonus = $list_nr_bonus[$idx_nr];
            
                    $flag_nr = self::generate_bonus( $user_id, $store_id, $arr_nrbonus );
                    if( $flag_nr ) {
                        $list_bonus['list'][] = $arr_nrbonus;
                        $num_bonus = $num_bonus - 1;
                        //unset($list_nr_bonus[$idx_nr]);
                        array_splice($list_nr_bonus, $idx_nr, 1);
            
                    }else {
                        $tip .= "{$arr_nrbonus['type_name']}[{$arr_nrbonus['bonus_id']}]领取红包失败; ";
                    }
            
                }while( !$flag_nr && $time_nr < $num_nrb*3 );

            }
            
        }
        
// w_log('cyb_log', '');
        
        return $list_bonus;
    }
    
    /**
     * 发放红包
     * @param number $user_id 用户ID;
     * @param number $store_id 店铺ID;
     * @param array $arr_bonus 红包信息;
     * @return bool flag 成功true; 失败false;
     * 
     * @author ^2_3^
     */
    private function generate_bonus( $user_id=0, $store_id=0, $arr_bonus=array() ) {
        $flag = false;
        if( empty($user_id) || empty($store_id) || empty($arr_bonus) ) {
            $str_arr_bonus = implode(',', $arr_bonus);
            throw new \Exception("提示:BlstoreController->generate_bonus({$user_id}, {$store_id}, {$str_arr_bonus})参数缺失;");
        }
        
        $use_start_date = $arr_bonus['use_start_date'];
        $use_end_date = $arr_bonus['use_end_date'];
        //-/ 领取期限
        if( $arr_bonus['has_effective_days'] ) {
            $days = empty($arr_bonus['effective_days']) ? 1 : $arr_bonus['effective_days'];
            $use_start_date = gmtime();
            $use_end_date = $use_start_date + $days * 86400;
        }
        
        $data_br = array(
            'user_id' => $user_id,
            'store_id' => $store_id,
            'bonus_id' => $arr_bonus['bonus_id'],
            'use_start_date' => $use_start_date,
            'use_end_date' => $use_end_date,
            'get_time' => gmtime(),
            'r_status' => 0
        );
        $flag = M('bl_bonus_record')->add($data_br);
        $flag = true;
        
        return $flag;
    }
    
    /**
     * 个人中心_红包列表
     * @param int store_id 便利店ID;
     * @param int store_sn 店铺货架编号; (store_id、store_sn至少一个)
     * @param int user_id 用户ID;
     *
     * @author ^2_3^
     */
    public function bonus_list() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where($where_s)->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此店铺,请联系客服;');
        }
        
        $time_now = gmtime();
        $where = array(
            'br.user_id' => $user_id,
            'br.use_start_date' => array('ELT', $time_now),
            'br.use_end_date' => array('GT', $time_now),
            'br.use_time' => 0,
            'br.r_status' => 0
        );
        $where['_string'] = " br.store_id = {$store_id} OR br.store_id = 0 ";
        $list = M('bl_bonus_record br')
            ->join('sdx_bonus_type bt ON bt.type_id = br.bonus_id', 'left')
            ->field('
                br.id,
            	br.user_id,
            	br.store_id,
            	br.bonus_id,
            	br.use_start_date,
            	br.use_end_date,
            	br.get_time,
                bt.type_name,
            	bt.min_goods_amount,
            	bt.type_money
            ')
            ->where($where)
            ->select();
// w_log('cyb_log', '红包列表 '.M()->getLastSql());

        foreach ( $list as $key=>$arr ){
            $list[$key]['get_date'] = local_date('Y-m-d H:i:s', $arr['get_time']);
        }

        if( empty($list) ) {
            $data['msg'] = '提示:没有红包;';
        }
        $data['list'] = $list;

        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 购物车_清空_商品
     * 
     * @param int store_id 便利店ID;
     * @param string store_sn 店铺货柜编号;
     * @param int user_id 用户ID;
     * 
     * @author ^2_3^
     */
    public function cart_empty() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where($where_s)->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此店铺,请联系客服;');
        }
        
        /// 清空操作
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        $f_cart = M('bl_cart')->where($where_c)->delete();
        if( $f_cart !== false ) {
            $data['msg'] = 'ok';
            returnApiSuccess($data);
        }else {
            returnApiError('提示:清空购物车失败,请联系客服;');
        }
    }
    
    /**
     * 购物车_减少_商品
     *
     * @param int store_id 便利店ID;
     * @param string store_sn 店铺货柜编号; (store_id、store_sn至少一个)
     * @param int user_id 用户ID;
     * @param int goods_id 商品ID;
     * @param string goods_sn 商品sn;
     *
     * @author ^2_3^
     */
    public function cart_minus() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');
        $goods_sn = I('post.goods_sn', '', 'string');
        if( (empty($store_id) && empty($store_sn)) || empty($user_id) || empty($goods_sn) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺验证
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where( $where_s )->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此便利店铺;');
        }
        
        /// 购物车操作
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        !empty($goods_id) && $where_c['goods_id'] = $goods_id;
        !empty($goods_sn) && $where_c['goods_sn'] = $goods_sn;
        $info_cart = M('bl_cart')->where( $where_c )->find();
        //-/ 减少商品
        if( $info_cart['goods_number'] > 1 ) {
            $flag = M('bl_cart')->where( $where_c )->setDec('goods_number');
            //-/ 商品信息
            $info_cart['goods_number'] = $info_cart['goods_number'] - 1;
            $info_goods = $info_cart;
            
        }else if( $info_cart['goods_number'] == 1 ) {
            $flag = M('bl_cart')->where( $where_c )->delete();
            //-/ 最近商品
            $where_c = array(
                'store_id' => $store_id,
                'user_id' => $user_id
            );
            $info_goods = M('bl_cart')->where($where_c)->order('rec_id desc')->find();
        }
        
        /// 购物车列表
        $num_goods = 0;
        $num_amount = 0;
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        $list_cart = M('bl_cart')->where( $where_c )->order('rec_id desc')->select();
        foreach ( $list_cart as $c_key=>$c_arr ){
            //-/ 商品个数
            $num_goods += $c_arr['goods_number'];
            //-/ 商品总额
            $num_amount += $c_arr['goods_price'] * $c_arr['goods_number'];
        }
        
        $data['num_goods'] = $num_goods;
        $data['num_amount'] = $num_amount;
        $data['info_goods'] = $info_goods;
        $data['list_cart'] = $list_cart;
        returnApiSuccess($data);
        
    }
    
    /**
     * 获取购物车列表
     *
     * @param int store_id 便利店ID;
     * @param string store_sn 店铺货柜编号; (store_id、store_sn至少一个)
     * @param int user_id 用户ID;
     *
     * @author ^2_3^
     */
    public function get_cart_list() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺验证
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where( $where_s )->find();
        if( empty($info_store) ) {
            returnApiError('提示:便利店铺识别失败,请重新识别;');
        }
        
        /// 购物车列表
        $num_goods = 0;
        $num_amount = 0;
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        $list_cart = M('bl_cart')->where( $where_c )->order('rec_id desc')->select();
        foreach ( $list_cart as $c_key=>$c_arr ){
            //-/ 商品个数
            $num_goods += $c_arr['goods_number'];
            //-/ 商品总额
            $num_amount += $c_arr['goods_price'] * $c_arr['goods_number'];
        }
        $data['num_goods'] = $num_goods;
        $data['num_amount'] = $num_amount;
        $data['list_cart'] = $list_cart;
        returnApiSuccess($data);
    }
    
    /**
     * 购物车_添加_商品
     * 
     * @param int store_id 便利店ID;
     * @param string store_sn 店铺货柜编号; (store_id、store_sn至少一个)
     * @param int user_id 用户ID;
     * @param int goods_id 商品ID;
     * @param string goods_sn 商品sn;
     * 
     * @author ^2_3^
     */
    public function cart_add() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        $goods_id = I('post.goods_id', 0, 'int');
        $goods_sn = I('post.goods_sn', '', 'string');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) || empty($goods_sn) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺验证
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where( $where_s )->find();
        if( empty($info_store) ) {
            returnApiError('提示:便利店铺识别失败,请重新识别;');
        }
        
        /// 商品验证
        $where_g = array();
        !empty($goods_id) && $where_g['g.goods_id'] = $goods_id;
        !empty($goods_sn) && $where_g['g.goods_sn'] = $goods_sn;
        $where_g['m.user_rank'] = 2; // 1注册用户;2VIP会员;
        //-/ 商品信息
        $info_goods = M('goods_wid_8')
            ->alias('g')
            ->field('g.*, m.user_price')
            ->join('sdx_member_price m ON g.goods_id = m.goods_id')
            ->where( $where_g )
            ->find();
// w_log('bl_log', 'blstore->cart_add() '.M()->getLastSql());
        if( empty($info_goods) ) {
            returnApiError('提示:商品识别失败，请重新扫描;');
            
        }/* else if( $info_goods['is_delete'] == 1 || $info_goods['is_on_sale'] == 0 ) {
            $data['goods_id'] = $info_goods['goods_id'];
            $data['goods_sn'] = $info_goods['goods_sn'];
            $data['goods_name'] = $info_goods['goods_name'];
            returnApiError('提示:此商品已下架,请联系客服;');
        } */
        //-/ 商品价格
        $info_goods['goods_price'] = $info_goods['user_price'];
        
        /// 购物车操作
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        !empty($goods_id) && $where_c['goods_id'] = $goods_id;
        !empty($goods_sn) && $where_c['goods_sn'] = $goods_sn;
        $info_cart = M('bl_cart')->where( $where_c )->find();
// w_log('bl_log', 'blstore->cart_add() 购物车操作 '.M()->getLastSql());
        //-/ 添加商品
        $f_cart = false;
        defined(SESS_ID) ? $sess_id = SESS_ID : $sess_id = '';
        if( empty($info_cart) ) {
            //-/ 新增商品
            $data_c = array(
                'store_id' => $store_id,
                'user_id' => $user_id,
                'session_id' => $sess_id,
                'goods_id' => $info_goods['goods_id'],
                'goods_sn' => $info_goods['goods_sn'],
                'goods_name' => $info_goods['goods_name'],
                'market_price' => $info_goods['market_price'],
                'goods_price' => $info_goods['user_price'],
                'goods_number' => 1,
                'is_real' => 1
            );
            $f_cart = M('bl_cart')->data( $data_c )->add();
            
        } else {
            //-/ 叠加商品
            $data_c = array(
                'session_id' => $sess_id,
                'market_price' => $info_goods['market_price'],
                'goods_price' => $info_goods['user_price'],
                'goods_number' => intval($info_cart['goods_number']) + 1
            );
            $f_cart = M('bl_cart')->where( $where_c )->save($data_c);
        }
        if( !$f_cart ) {
            returnApiError('提示:添加商品失败,请联系客服;');
        }
        
        /// 购物车列表
        $num_goods = 0;
        $num_amount = 0;
        $where_c = array(
            'store_id' => $store_id,
            'user_id' => $user_id
        );
        $list_cart = M('bl_cart')->where( $where_c )->order('rec_id desc')->select();
        foreach ( $list_cart as $c_key=>$c_arr ){
            //-/ 商品个数
            $num_goods += $c_arr['goods_number'];
            //-/ 商品总额
            $num_amount += $c_arr['goods_price'] * $c_arr['goods_number'];
        }
        
        $data['num_goods'] = $num_goods;
        $data['num_amount'] = $num_amount;
        $data['info_goods'] = $info_goods;
        $data['list_cart'] = $list_cart;
        returnApiSuccess($data);
    }
    
    /**
     * 订单提交(结算)
     * 
     * @param int store_id 便利店ID;
     * @param string store_sn 店铺货柜编号; (store_id、store_sn至少一个)
     * @param int user_id 用户ID;
     * @param int bonus_id 红包ID;
     * @param int br_id 红包领取记录ID;
     * 
     * @author ^2_3^
     */
    public function order_submit() {
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $user_id = I('post.user_id', 0, 'int');
        $bonus_id = I('post.bonus_id', 0, 'int');
        $br_id = I('post.br_id', 0, 'int');
        if( ( empty($store_id) && empty($store_sn) ) || empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where( $where_s )->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此店铺,请联系客服;');
            
        }else if( $info_store['store_status'] == 1 ) {
            returnApiError('提示:店铺已经禁用,请联系客服;');
        }
        
        /// 购物列表
        $where_c = array(
            'store_id' => $info_store['id'],
            'user_id' => $user_id
        );
        $list_cart = M('bl_cart')
            ->alias('c')
            ->join('sdx_goods_wid_8 g ON g.goods_id = c.goods_id', 'left')
            ->field('c.*, g.is_delete, g.is_on_sale')
            ->where( $where_c )
            ->select();
// w_log('cyb_log', 'Blstore->order_submit '.M()->getLastSql());
        if( empty($list_cart) ) {
            returnApiError('提示:还没有选择商品, 不能提交订单;');
        }
        //-/ 商品处理
        $goods_amount = 0;
        foreach ( $list_cart as $c_key=>$c_arr ){
            //-/ 商品验证: 有删除/下架商品不能提交;
//             if( $c_arr['is_delete'] == 1 || $c_arr['is_on_sale'] == 0 ) {
//                 $data['goods_id'] = $c_arr['goods_id'];
//                 $data['goods_sn'] = $c_arr['goods_sn'];
//                 $data['goods_name'] = $c_arr['goods_name'];
//                 returnApiError('提示:有商品已下架, 不能提交;', $data);
//             }
            
            //-/ 订单商品总额
            $goods_amount += $c_arr['goods_price'] * $c_arr['goods_number'];
            
        }
        
        /// 用户信息
        $where_u = array(
            'user_id' => $user_id
        );
        $info_user = M('users')->where( $where_u )->find();
        if( empty($info_user) ) {
            returnApiError('提示:获取用户信息失败,请重试;');
        }
        
        /// 红包处理
        $info_bonus = array();
        $bonus_money = 0;
        $b_id = 0;
        $brecord_id = 0;
        if( !empty($bonus_id) && !empty($br_id) ) {
            $where_b = array(
                'br.user_id' => $user_id,
                'br.bonus_id' => $bonus_id,
                'br.id' => $br_id
            );
            $where_b['_string'] = " br.store_id = {$info_store['id']} OR br.store_id = 0 ";
            $info_bonus = M('bl_bonus_record')->alias('br')
                ->join( 'sdx_bonus_type bt ON bt.type_id = br.bonus_id' )
                ->field('
                    br.id,
                    br.user_id,
                    br.store_id,
                    br.bonus_id,
                    br.use_start_date,
                    br.use_end_date,
                    br.get_time,
                    br.use_time,
                    br.r_status,
                    bt.type_name,
                    bt.type_money,
                    bt.min_goods_amount
                ')
                ->where($where_b)
                ->find();
            
            $time_now = gmtime();
            if( empty($info_bonus) ) {
                returnApiError('提示: 没找到此红包,请稍后重试;');
                
            } else if( !empty($info_bonus['use_time']) ) {
                returnApiError('提示: 此红包已经使用;');
                
            } else if( $time_now < $info_bonus['use_start_date'] 
                || $time_now > $info_bonus['use_end_date'] || $info_bonus['r_status'] == 1 ) {
                returnApiError('提示: 此红包不在红包使用期内, 请重新下单;');
                
            } else if( $goods_amount < $info_bonus['min_goods_amount'] ) {
                returnApiError('提示: 订单总额没满足红包最低使用额度;');
            }
            
            /// 判断是否已经使用
            $where_oi = array(
                'pay_status' => 2,
                'order_status' => 1,
                'br_id' => $br_id,
                'bonus_id' => $bonus_id
            );
            $info_order = M('bl_order_info')->where($where_oi)->find();
            if( !empty($info_order) ) {
                returnApiError('提示: 红包已使用;');
            }
            
            /// 规则: 每个用户每日最多只能用两次红包;
            $date = date('Y-m-d');
            $time_today = gmstr2time($date);
            $where_boi = array(
                'order_status'  => 1,
                'pay_status'    => 2,
                'add_time'      => array('EGT', $time_today),
                'user_id'       => $user_id,
                'store_id'      => $info_store['id'],
                'bonus_id'      => array('NEQ', 0),
                'br_id'         => array('NEQ', 0)
            );
            $count_boi = M('bl_order_info')->where( $where_boi )->count();
            if( $count_boi >= 2 ) {
                returnApiError('提示: 每日不能超过2次红包使用哦!');
            }
            
            $bonus_money = $info_bonus['type_money'];
            $b_id = $info_bonus['bonus_id'];
            $brecord_id = $br_id;
            
        }else if( (!empty($bonus_id) && empty($br_id)) || (empty($bonus_id) && !empty($br_id)) ) {
            returnApiError('提示: 红包参数缺失;');
        }
        
        /// 订单操作
        M()->startTrans();
        $time_opt = gmtime();
        $order_sn = get_order_sn();
        //-/ 订单信息
        $data_oi = array(
            'order_sn' => $order_sn,
            'store_id' => $info_store['id'],
            'user_id' => $user_id,
            'consignee' => $info_user['user_name'],
            'address' => $info_store['address'],
            'mobile' => $info_user['mobile_phone'],
            'goods_amount' => $goods_amount,
            'order_amount' => $goods_amount - $bonus_money,
            'bonus_id' => $b_id,
            'br_id' => $brecord_id,
            'bonus' => $bonus_money,
            'referer' => "H5-便利店-{$info_store['id']}",
            'add_time' => $time_opt,
            'longitude' => $info_store['longitude'],
            'latitude' => $info_store['latitude']
        );
        $f_oi = M('bl_order_info')->data( $data_oi )->add();
// w_log('cyb_log', 'Blstore->order_submit oi '.M()->getLastSql());
        //-/ 订单商品
        $data_og = array();
        foreach ( $list_cart as $key=>$arr ){
            $data_tmp = array(
                'order_id' => $f_oi,
                'goods_id' => $arr['goods_id'],
                'goods_name' => $arr['goods_name'],
                'goods_sn' => $arr['goods_sn'],
                'goods_number' => $arr['goods_number'],
                'market_price' => $arr['market_price'],
                'goods_price' => $arr['goods_price'],
                'is_real' => 1
            );
            $data_og[] = $data_tmp;
        }
        $f_og = M('bl_order_goods')->addAll( $data_og );
// w_log('cyb_log', 'Blstore->order_submit og '.M()->getLastSql());
        
        if( $f_oi && $f_og ) {
            M()->commit();
            
            /// 标记红包使用(支付成功才标识, 固注释)
//             if( !empty($bonus_id) && !empty($br_id) ) {
//                 $where_b = array(
//                     'user_id' => $user_id,
//                     'store_id' => $info_store['id'],
//                     'bonus_id' => $bonus_id,
//                     'id' => $br_id
//                 );
//                 $data_b = array(
//                     'use_time' => $time_opt
//                 );
//                 $f_br = M('bl_bonus_record')->where($where_b)->save($data_b);
//             }
            
            /// 清空购物车
            $where_c = array(
                'store_id' => $info_store['id'],
                'user_id' => $user_id
            );
            $f_cart = M('bl_cart')->where($where_c)->delete();
            
            $data['order_id'] = $f_oi;
            $data['order_sn'] = $order_sn;
            $data['order_amount'] = $goods_amount;
            returnApiSuccess($data, '订单提交成功;');
            
        }else {
            M()->rollback();
            returnApiError('提示:提交订单失败,请联系客服;');
        }
    }
    
    /// --店铺_商品_上架、下架、盘点-- ///
    
    /**
     * 店铺列表
     * @link http://apidev.cyb.cn/index.php?s=/blstore/store_list/
     * 
     * @param int user_id 便利店铺_管理人员_用户ID(访问微商用户ID);
     * @param int page 第几页,默认为1, 表示第一页;
     * 
     * @author ^2_3^
     */
    public function store_list() {
        $start = microtime(true);
        if( !IS_POST ) {
           returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $user_id = I('post.user_id', 0, 'int');
        if( empty($user_id) ) {
            returnApiError('提示:参数缺失;');
        }
        $page = I('post.page', 1, 'int');
        empty($page) && $page = 1;
        
        /// 验证用户_是否为管理员
        $flag_user = self::is_bl_msg($user_id);
        if(!$flag_user) {
            returnApiError('提示:你不是店铺管理人员;');
        }
        
        /// 店铺列表
        $where = array(
            'mp.user_id' => $user_id,
            'mp.user_status' => 0,
            's.store_status' => 0
        );
        //-/ 店铺分页
        // 店铺数量
        $count_store = M('bl_store s')
            ->join('sdx_bl_msg_person mp ON mp.store_id = s.id')
            ->where($where)
            ->count('s.id');
// w_log('cyb_log', '店铺数量 '.M()->getLastSql());
        $data['count_store'] = $count_store;
        // 大小
        $page_size = 10;
        $data['page_size'] = $page_size;
        // 页面总数
        $page_count = ceil($count_store / $page_size);
        $data['page_count'] = $page_count;
        // 是否底部
        if( $page >= $page_count){
            $is_bottom = 1;
        }else{
            $is_bottom = 0;
        }
        $data['is_bottom'] = $is_bottom;
        // 限制条件
        $limit_begin = ($page-1) * $page_size;
        $limit = " {$limit_begin}, {$page_size} ";
        //-/ 店铺列表
        $list_store = M('bl_store s')
            ->field("
                s.id AS store_id,
            	s.store_name,
                s.store_sn,
            	s.img_url,
            	s.linkman,
            	s.link_mobile,
            	s.store_status,
            	s.create_time,
            	mp.user_id,
            	mp.user_status
            ")
            ->join('sdx_bl_msg_person mp ON mp.store_id = s.id')
            ->where($where)
            ->limit( $limit )
            ->order('s.create_time ASC')
            ->select();
// w_log('cyb_log', '店铺列表 '.M()->getLastSql());
        foreach ( $list_store as $key=>$arr ){
            //-/ 店铺状态
            $store_status_text = '';
            if( $arr['store_status'] == 0 ) {
                $store_status_text = '启用';
            }else {
                $store_status_text = '禁用';
            }
            $list_store[$key]['store_status_text'] = $store_status_text;
            
            //-/ 管理人员状态
            $user_status_text = '';
            if( $arr['user_status'] == 0 ) {
                $user_status_text = '启用';
            }else {
                $user_status_text = '禁用';
            }
            $list_store[$key]['user_status_text'] = $user_status_text;
            
            //-/ 店铺创建时间
            $list_store[$key]['create_date'] = local_date('Y-m-d H:i:s', $arr['create_time']); 
        }
        $data['list_store'] = $list_store;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess($data);
    }
    
    /**
     * 店铺管理_商品上架/下架/盘点
     * @link http://apidev.cyb.cn/index.php?s=/blstore/store_goods_opn/
     * 
     * @param int user_id 用户ID;
     * @param int store_id 店铺ID;
     * @param string store_sn 店铺货柜编号; (store_id、store_sn至少一个)
     * @param int goods_id 上下架商品ID;
     * @param string goods_sn 上下架商品货号;
     * @param string opt_type 操作类型, 1上架; 2下架; 3盘点; 4查询;
     * @param int opn_num 本次操作数量;
     * 
     * @author ^2_3^
     */
    public function store_goods_opn() {
        $start = microtime(true);
        if( !IS_POST ) {
            returnApiError('提示:无效请求;');
        }
        
        /// 参数处理
        $user_id = I('post.user_id', 0, 'int');
        $store_id = I('post.store_id', 0, 'int');
        $store_sn = I('post.store_sn', '', 'trim');
        $goods_id = I('post.goods_id', 0, 'int');
        $goods_sn = I('post.goods_sn', '', 'trim');
        $opt_type = I('post.opt_type', 0, 'int');
        $opn_num = I('post.opn_num', 0, 'int');
        if( empty($user_id) || (empty($store_id) && empty($store_sn)) || ( empty($goods_id) && empty($goods_sn) )
            || !in_array($opt_type, array(1, 2, 3, 4)) ) {
            returnApiError('提示:参数缺失;');
        }
        
        /// 店铺信息
        $where_s = array();
        if( !empty($store_id) ) {
            $where_s['id'] = $store_id;
        }
        if( !empty($store_sn) ) {
            $where_s['store_sn'] = $store_sn;
        }
        $info_store = M('bl_store')->where($where_s)->find();
        if( empty($info_store) ) {
            returnApiError('提示:没有此店铺,请联系客服;');
        }
        
        /// 店铺-人员信息
        $arr_info = self::get_store_msg_info($info_store['id'], $user_id);
        if( empty($arr_info) ) {
            returnApiError('提示:参数错误, 没有此便利店铺;');
            
        }else if( empty($arr_info['user_id']) ) {
            returnApiError('提示:此用户不是该店铺货架管理人员;');
            
        }else if( $arr_info['store_status'] == 1 ) {
            returnApiError('提示:店铺已经禁用;');
            
        }else if( $arr_info['user_status'] == 1 ) {
            returnApiError('提示:该管理账号已经禁用;');
        }
        $data['info_store'] = $arr_info;
        
        /// 商品信息
        $where_g = array();
        if( !empty($goods_id) ) {
            $where_g['goods_id'] = $goods_id;
        }
        if( !empty($goods_sn) ) {
            $where_g['goods_sn'] = $goods_sn;
        }
        $info_goods = M('goods')
            ->field('
                goods_id,
                goods_sn,
                goods_name
            ')
            ->where($where_g)
            ->find();
        if( empty($info_goods) ) {
            returnApiError('提示:没有找到此商品;');
        }

        /// 上架操作
        if( $opt_type == 1 ) {
            //-/ 添加上架记录
            $data_gor = array(
                'store_id' => $info_store['id'],
                'goods_id' => $info_goods['goods_id'],
                'goods_name' => $info_goods['goods_name'],
                'goods_sn' => $info_goods['goods_sn'],
                'opn_type' => 1,
                'opn_num' => intval($opn_num),
                'user_id' => $user_id,
                'opn_time' => gmtime()
            );
            $f_gor = M('bl_goods_opn_record')
                ->data($data_gor)
                ->add();
            $f_gor === false && returnApiError('提示:商品上架失败;');

        /// 下架操作
        }else if( $opt_type == 2 ) {
            //-/ 添加下架记录
            $data_gor = array(
                'store_id' => $info_store['id'],
                'goods_id' => $info_goods['goods_id'],
                'goods_name' => $info_goods['goods_name'],
                'goods_sn' => $info_goods['goods_sn'],
                'opn_type' => 2,
                'opn_num' => intval($opn_num),
                'user_id' => $user_id,
                'opn_time' => gmtime()
            );
            $f_gor = M('bl_goods_opn_record')
                ->data($data_gor)
                ->add();
            $f_gor === false && returnApiError('提示:商品下架失败;');
            
        }
        
        //// 应在架数量 = 商品上架数量 - 销售数量 - 下架商品数量;
        /// 商品上架/下架数量
        $where_gor = array(
            'gor.opn_type' => array('IN', '1, 2'),
            'gor.store_id' => $info_store['id']
        );
        if( !empty($goods_id) ) {
            $where_gor['goods_id'] = $goods_id;
        }
        if( !empty($goods_sn) ){
            $where_gor['goods_sn'] = $goods_sn;
        }
        $list_gor = M('bl_goods_opn_record gor')
            ->field('
                gor.store_id,
            	gor.goods_id,
            	gor.goods_name,
            	gor.goods_sn,
            	gor.opn_type,
            	SUM( gor.opn_num ) AS sum_opn_num
            ')
            ->where( $where_gor )
            ->group( 'gor.opn_type' )
            ->select();
        // 上架数量
        $num_up = 0;
        // 下架数量
        $num_down = 0;
        foreach ( $list_gor as $key=>$arr ){
            //-/ 上架
            if( $arr['opn_type'] == 1 ) {
                $num_up = $arr['sum_opn_num'];
                
            //-/ 下架
            }else if( $arr['opn_type'] == 2 ) {
                $num_down = $arr['sum_opn_num'];
            }
        }
        
        /// 销售数量
        $where_oi = array(
            'oi.pay_status' => 2,
            'oi.store_id' => $info_store['id']
        );
        if( !empty($goods_id) ) {
            $where_oi['goods_id'] = $goods_id;
        }
        if( !empty($goods_sn) ) {
            $where_oi['goods_sn'] = $goods_sn;
        }
        $arr_sale = M('bl_order_info oi')
            ->join('sdx_bl_order_goods og ON og.order_id = oi.order_id')
            ->field('
            	og.goods_id,
            	og.goods_name,
            	og.goods_sn,
            	SUM(og.goods_number) AS sum_goods_number
            ')
            ->where( $where_oi )
            ->find();
        // 销售数量
        $num_sale = 0;
        !empty($arr_sale['sum_goods_number']) && $num_sale = $arr_sale['sum_goods_number'];
        
        /// 应在架数
        $num_on = $num_up - $num_down - $num_sale;
        
        /// 盘点差值 = 本次盘点操作数量 - 应在架数量;
        $num_dif = 0;
        if( $opt_type == 3 ) {
            $num_dif = $opn_num - $num_on;
            
            //-/ 添加盘点记录
            $data_gor = array(
                'store_id' => $info_store['id'],
                'goods_id' => $info_goods['goods_id'],
                'goods_name' => $info_goods['goods_name'],
                'goods_sn' => $info_goods['goods_sn'],
                'opn_type' => 3,
                'opn_num' => intval($opn_num),
                'opn_num_dif' => $num_dif,
                'opn_note' => "上架[{$num_up}]; 下架[{$num_down}]; 销售[{$num_sale}];",
                'user_id' => $user_id,
                'opn_time' => gmtime()
            );
            $f_gor = M('bl_goods_opn_record')
                ->data($data_gor)
                ->add();
            $f_gor === false && returnApiError('提示:商品盘点失败;');
        }
        
        $data['opt_type'] = $opt_type;
        $data['num_up'] = $num_up;
        $data['num_down'] = $num_down;
        $data['num_sale'] = $num_sale;
        $data['num_on'] = $num_on;
        $data['num_dif'] = $num_dif;
        $data['info_goods'] = $info_goods;
        
        $data['msg'] = "提示: 操作成功!";
        $end = microtime(true);
        $data['time'] = $end - $start;
        returnApiSuccess( $data );
    }
    
    /**
     * 获取店铺及人员信息
     * 
     * @param number $store_id 店铺ID;
     * @param number $user_id 管理人员ID;
     * @return array 店铺-人员信息;
     * 
     * @author ^2_3^
     */
    private function get_store_msg_info($store_id=0, $user_id=0) {
        $arr_info = array();

        /// 参数验证
        if( empty($store_id) || empty($user_id) ) {
            throw new \Exception('错误:Blstore->get_store_msg_info()缺少参数;');
        }
        
        //-/ 店铺人员信息
        $where = array(
            's.id' => $store_id
        );
        $arr_info = M('bl_store s')
                ->field("
                    s.id AS store_id,
                	s.store_name,
                    s.store_sn,
                	s.img_url,
                	s.linkman,
                	s.link_mobile,
                	s.store_status,
                	s.create_time,
                	mp.user_id,
                	mp.user_status
                ")
                ->join("sdx_bl_msg_person mp ON mp.store_id = s.id AND mp.user_id = {$user_id} ", 'left')
                ->where($where)
                ->find();
// w_log('cyb_log', '店铺人员信息 '.M()->getLastSql());
        
        return $arr_info;
    }
    
    /**
     * 验证用户_是否为便利店铺管理员
     * 
     * @param int user_id 用户ID;
     * @return bool $flag 是true, 否false;
     * 
     * @author ^2_3^
     */
    private function is_bl_msg( $user_id = 0 ) {
        $flag = false;
        if( empty($user_id) ) {
            throw new \Exception('错误:Blstore->is_bl_msg()缺少user_id参数;');
        }
        
        $where = array(
            'user_id' => $user_id
        );
        $arr = M('bl_msg_person')->where($where)->find();
        
        if( is_array($arr) && !empty($arr) ) {
            $flag = true;
        }
        
        return $flag;
    }
    
    /**
     * [API]线下红包领取
     * @link http://apidev.cyb.cn/index.php?s=/blstore/get_bonus_by_bonusid/
     * 
     * @param int userid 用户ID;
     * @param int bonusid 红包ID;
     * @author ^2_3^
     */
    public function get_bonus_by_bonusid() {
        $data['status'] = 0;
        $data['msg'] = '';
        if( !IS_POST ) {
            $data['msg'] = '提示: 无效请求;';
            returnApiError( $data['msg'] );
        }
        
        /// 参数处理
        $userid = I('post.userid', 0, 'int');
        $bonusid = I('post.bonusid', 0, 'int');
        if( empty($userid) || empty($bonusid) ) {
            $data['msg'] = '提示: 参数缺失;';
            returnApiError( $data['msg'] );
        }
        
        /// 红包信息
        $info_bonus = M('bonus_type bt')
            ->join('sdx_bl_bonus_set bs ON bs.bonus_id = bt.type_id', 'left')
            ->field('
                bs.id AS bs_id,
            	bs.bonus_tip_name,
            	bs.is_disabled,
            	bs.bl_bonus_type,
            	bt.type_id AS bonus_id,
            	bt.type_name AS bonus_name,
            	bt.type_money,
            	bt.send_start_date,
            	bt.send_end_date,
            	bt.use_start_date,
            	bt.use_end_date,
            	bt.min_goods_amount,
            	bt.send_num,
            	bt.limit_send_num,
            	bt.has_effective_days,
            	bt.effective_days,
            	bt.b_use_type
            ')
            ->where(array('bt.type_id' => $bonusid))
            ->find();
        if( empty($info_bonus) ) {
            $data['msg'] = "提示: 红包参数无效({$bonusid});";
            returnApiError( $data['msg'] );
        }
        
        /// 红包验证
        $time_now = gmtime();
        if( $info_bonus['is_disabled'] == 1 ) { //-/是否禁用, 默认0不禁用; 1禁用;
            $data['msg'] = "提示: 活动已结束, 期待下次({$bonusid});";
            returnApiError( $data['msg'] );
            
        }else if( $info_bonus['bl_bonus_type'] == 0 ) { //红包类型, 默认为0; 0线上; 1线下;
            $data['msg'] = "提示: 此为线上红包({$bonusid});";
            returnApiError( $data['msg'] );
            
        }else if( !empty($info_bonus['send_start_date']) && $time_now < $info_bonus['send_start_date'] ) {
            $send_start_date = local_date('Y-m-d H:i:s', $info_bonus['send_start_date']);
            $data['msg'] = "提示: {$send_start_date}才开始哦({$bonusid});";
            returnApiError( $data['msg'] );
            
        }else if( !empty($info_bonus['send_end_date']) && $time_now > $info_bonus['send_end_date'] ) {
            $data['msg'] = "提示: 活动已结束哦, 期待再见({$bonusid});";
            returnApiError( $data['msg'] );
            
        }else if( $info_bonus['b_use_type'] == 0 ) { //红包用途, 0默认; 1便利店铺红包;
            $data['msg'] = "提示: 无效红包, 期待再见({$bonusid});";
            returnApiError( $data['msg'] );
        }
        
        /// 红包数量限制
        $count_num = M('bl_bonus_record br')
            ->where( array('bonus_id'=>$info_bonus['bonus_id']) )
            ->count('id');
        if( !empty($info_bonus['limit_num']) && $count_num > $info_bonus['limit_num'] ) {
            $data['msg'] = "提示: 红包已经被领完, 期待再见;";
            returnApiError( $data['msg'] );
        }
        
        /// 判断是否已经领取
        $count_ub = M('bl_bonus_record')->where( array('user_id'=> $userid, 'bonus_id'=> $bonusid) )->count('id');
        if( $count_ub > 0 ) {
            $data['msg'] = "提示: 请勿重复领取红包哦({$bonusid});";
            returnApiError( $data['msg'] );
        }
        
        /// 领取红包
        if( $info_bonus['has_effective_days'] && !empty($info_bonus['effective_days']) ) {
            $use_start_time = $time_now;
            $use_end_time = $use_start_time + $info_bonus['effective_days'] * 86400;
            
        }else if( !empty($info_bonus['send_start_date']) && !empty($info_bonus['send_end_date']) ) {
            $use_start_time = $info_bonus['send_start_date'];
            $use_end_time = $info_bonus['send_end_date'];
            
        }else {//默认七天过期
            $use_start_time = $time_now;
            $use_end_time = $use_start_time + 7 * 86400;
        }
        $data_bonus = array(
            'user_id' => $userid,
            'bonus_id' => $info_bonus['bonus_id'],
            'bonus_money' => $info_bonus['type_money'],
            'order_money' => $info_bonus['min_goods_amount'],
            'use_start_date' => $use_start_time,
            'use_end_date' => $use_end_time,
            'get_time' => $time_now
        );
        $flag = M('bl_bonus_record')->add( $data_bonus );
        
        if( $flag ) {
            $data['msg'] = "提示: 红包领取成功;";
            returnApiSuccess($data);
            
        }else {
            $data['msg'] = "提示: 红包领取失败, 稍后重试;";
            returnApiError( $data['msg'] );
        }
        
    }
    
}